package org.ogv.usada.views;

import org.ogv.OGV;
import org.ogv.usada.models.Content;
import org.ogv.usada.models.IllnessDef;
import org.ogv.usada.models.LeafDef;
import org.ogv.usada.models.Recipe;

import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class CustomerBubble extends Sprite {

	private IllnessDef 		_illnessDef;
	private Recipe			_recipe;
	private boolean			_recipeVisible;
	private TextureRegion[]	_leavesTex;

	public CustomerBubble() {
		super(OGV.asset.getTextureRegion(new String[] {"data/pack", "ui-bubble"}));
	}
	
	public void init(IllnessDef def, Recipe recipe) {
		_illnessDef 	= def;
		_recipe			= recipe;
		_recipeVisible	= false;
	}
	
	public void recipeVisible(boolean val) {
		_recipeVisible = val;
	}
	
	@Override
	public void draw(SpriteBatch spriteBatch) {
		super.draw(spriteBatch);

		if(_recipeVisible) drawRecipe(spriteBatch);
		else drawIllness(spriteBatch);
	}

	private void drawRecipe(SpriteBatch spriteBatch) {
		boolean[] 	mask = _recipe.getMask();
		byte[]		leaf = _recipe.getDef().leafIds;
		LeafDef[]	defs = Content.$().leaves;
		float cx 		= getX() + getWidth() * 0.5f;
		float cy 		= getY() + getHeight() * 0.5f;
		float texWidth	= defs[0].getSmallTexture().getRegionWidth();
		float texHeight	= defs[0].getSmallTexture().getRegionHeight();
		int col = 3;
		int row = leaf.length / col;
		
		for(int i = 0; i < leaf.length; i += col) {
			int itemLeft = leaf.length - i;
			int numItem = col - itemLeft > 0 ? itemLeft : col;

			float offsetX = cx - texWidth * numItem * 0.5f + 10;
			float offsetY = cy - (row * texHeight) + (texHeight * i/col);
			for(int j = 0; j < numItem; ++j) {
				int k = j + i;
				if(!mask[k]) {
					spriteBatch.draw(defs[leaf[k]].getSmallTexture(), offsetX + (j - 0.5f) * texWidth, offsetY);
				}
			}
		}
	}

	private void drawIllness(SpriteBatch spriteBatch) {
		TextureRegion tex = _illnessDef.getIcon();
		spriteBatch.draw(
			_illnessDef.getIcon(), 
			getX() + ((-tex.getRegionWidth() + (int)getWidth()) >> 1), 
			getY() + ((-tex.getRegionHeight() + (int)getHeight()) >> 1)
		);
	}
}
